from .models import *
from rest_framework import serializers
import re
from rest_framework.validators import ValidationError

class UserSer(serializers.ModelSerializer):
                                                    # 只做输入
    password = serializers.CharField(max_length=64,write_only=True, trim_whitespace=True)

    def validate(self,data):
        username = data.get("username")
        password = data.get("password")
        mobile = data.get("mobile")
        email = data.get("email")

        # 验证用户名是否满足要求
        if not re.findall(r"^\w{5,20}$", username):
            raise ValidationError("用户名是5到20为数字、字母或下划线")

        # 验证密码是否满足要求
        elif not re.findall(r'^[\w!@#$%^&*]{8,20}$',password):
            raise ValidationError("密码是8到20位数字、字母或下划线以及特殊!@#$%^&*符号")

        # 验证手机号是否满足要求
        elif not re.findall(r"^1[34578]\d{9}$",mobile):
            raise ValidationError("手机格式不正确")

        else:
            return data

    # 重写create方法
    def create(self, validated_data):
        user = User.objects.create_user(**validated_data)

        # 更新密码为哈希加密的
        # user.set_password(validated_data.get("password"))

        return user

    class Meta:
        model = User
        fields = ["id",'username','password','mobile','email']
        read_only_fields = ["id",]


class UserAvatarSer(serializers.ModelSerializer):
    user_name = serializers.SerializerMethodField(read_only=True)
    def get_user_name(self, obj):
        return obj.user.username
    class Meta:
        model = UserAvatar
        fields = "__all__"


# 权限的序列化器
class PermissionSer(serializers.ModelSerializer):
    type_name = serializers.PrimaryKeyRelatedField(queryset=PermissionType.objects.all())

    typename = serializers.SerializerMethodField(read_only=True)
    def get_typename(self, obj):
        return obj.type_name.name


    class Meta:
        model = Permission
        fields = "__all__"
        read_only_fields = ["id", ]


class PermissionTypeSer(serializers.ModelSerializer):

    class Meta:
        model = PermissionType
        fields = "__all__"
        read_only_fields = ["id",]